<html>
<head>
    <title>用户维护</title>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="../../images/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="../../../res/layui/css/layui.css" media="all"/>
    <script type="text/javascript" src="../../../res/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="../../../res/layui/layui.js" charset="utf-8"></script>
    <style>
        /*a  upload js代码 */
        .a-upload {
            padding: 4px 10px;
            height: 40px;
            line-height: 30px;
            position: relative;
            left: 150px;
            top: -60px;
            cursor: pointer;
            color: #888;
            background: #fafafa;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            display: inline-block;
            *display: inline;
            *zoom: 1
        }

        .a-upload  input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
            filter: alpha(opacity=0);
            cursor: pointer
        }

        .a-upload:hover {
            color: #444;
            background: #eee;
            border-color: #ccc;
            text-decoration: none
        }
        .input-group{
            position: absolute;
            left:-150px;
            top:55px;
        }
        #prePic{
            position: absolute;
            left: 170px;
            top: 0px;
        }
        /*调整返回所有角色高度*/
        .layui-form-checkbox i{
            height: 28px;
        }
    </style>
</head>
<body style="padding-top: 30px;height:100%">

<form class="layui-form" action="" method="post"  lay-filter="myfrom" id="myfrom1">
    <input type="hidden" name="userId" id="userId">
    <input type="hidden" name="userImg">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 90px;">公    司</label>
        <div class="layui-input-inline" style="width: 260px">
            <select name="companyId" id="companyId" lay-verify="required" lay-search="">
                <option value="0">总公司</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 90px;">用户名</label>
        <div class="layui-input-inline">
            <input type="text" id="userName"   name="userName" maxlength="20" style="width: 280px" lay-verify="required|title" lay-reqtext="用户真实姓名是必填项，岂能为空？" placeholder="请输入名称" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 90px;">用户密码</label>
        <div class="layui-input-inline">
            <input type="text" name="userPassword"  style="width: 280px" lay-verify="required|number" lay-reqtext="用户密码是必填项，岂能为空？" placeholder="请输入密码" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 90px;">用户手机号</label>
            <div class="layui-input-inline">
                <input type="tel" name="userPhone" style="width: 280px" lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 90px;">用户邮箱</label>
            <div class="layui-input-inline">
                <input type="tel" name="userMail" style="width: 280px" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>


    <div class="layui-form-item" style="height: 95px;">
        <label class="layui-form-label" style="width: 90px;padding-top: 40px">会员头像</label>
        <div class="layui-input-inline" style="position: relative;top: 30px;">
            <div class="input-group">
                <a href="javascript:;" class="a-upload"> <input type="file" name="imgFile" id="imgFile" >点击这里上传文件</a>
            </div>
        </div>
        <div class="layui-form-mid layui-word-aux"><img src="" id="prePic" width="90px" height="90px"></div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 90px;">是否有效</label>
        <div class="layui-input-inline">
            <select name="whetherValid" lay-filter="aihao">
                <option value="1" selected="">是</option>
                <option value="0">否</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 90px;">角色</label>
            <div id="roles" lay-filter="roles" class="layui-input-block" style="width:360px;text-align: left;position: relative;left: 10px;" >

            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-primary" id="cancel">取消</button>
            <button type="button" class="layui-btn" lay-submit="" lay-filter="myform">立即提交</button>
        </div>
    </div>

</form>
</body>

<script>
    layui.use(['form', 'layedit', 'laydate'], function(){
        var form = layui.form
            ,layer = layui.layer
            ,layedit = layui.layedit
            ,laydate = layui.laydate;


        $.ajax({
            async : false,
            dataType: "json",
            data:null,
            type : "POST",
            url : "/perRole/showAllRole",
            success:function (obj1) {
                console.info(obj1)
                var htmlStr = '';
                $.each(obj1,function (index,item) {
                    //console.info(item);
                    htmlStr+=`<input type="checkbox" name="role" value="${item.roleId}" title="${item.roleName}" >`;
                })
                $("#roles").html(htmlStr);
                form.render('checkbox');//刷新值
            },
            error:function () {

            }
        })
        //取消关闭窗口
        $('#cancel').on("click", function () {
            parent.closeCancel();
        });


        //自定义验证规则
        form.verify({
            title: function(value){
                if(value.length < 1){
                    return '标题至少得1个字符啊';
                }
            }
            ,number: [
                /^[\S]{6,12}$/
                ,'密码必须6到12位，且不能出现空格'
            ]
            ,content: function(value){
                layedit.sync(editIndex);
            }
        });


        let num = 0;
        //监听提交
        form.on('submit(myform)', function(data){
            num++;
            //只能点击一次
            if(num==1) {
                //判断用户名是否存在
                $.post("/perUsers/findUserName", {
                    userName: $("#userName").val(),
                    userId: $("#userId").val()
                }, function (obj) {
                    if (obj.status > 0) {
                        num = 0;
                        layer.msg(obj.message);
                    } else {
                        var url = "/perUsers/addOrrUpdateUser";
                        var formData = new FormData(document.getElementById("myfrom1"));
                        $.ajax({
                            url: url,
                            data: formData,
                            processData: false,
                            contentType: false,
                            dataType: 'json',
                            type: 'POST',
                            success: function (obj) {
                                console.info(obj);
                                if (obj.status == 1) {
                                    //关闭当前弹出层
                                    //parent.closeOpen("保存成功");
                                    parent.closeOpen(obj.message);
                                } else if (obj.status == 6) {
                                    layer.msg(obj.message);
                                } else {
                                    parent.closeOpen(obj.message);
                                }
                            },
                            error: function () {

                            }
                        })
                        return false;
                    }
                }, "json");
            }
        });


        /**
         * 查询所有分公司
         */
        $.ajax({
            async : false,
            url:"/hqImm/queryAll",
            dataType:"json",
            data:'',
            type:"post",
            success:function (res) {
                console.info(res)
                $.each(res,function (index,item) {
                    $("#companyId").append(`<option value="${item.immId}">${item.immName}</option>`);
                })
                form.render("select");
            },
            error:function () {

            }
        })


        //表单赋值
        var id = getQueryString("id");
        if(id){
           // $("#userName").prop("disabled","disabled");
            $("#userName").attr("class","layui-input layui-disabled");
            $("#userName").attr("readonly","readonly");
            var url = "/perUsers/findByUsersId";
            var data = {id : id};
            $.ajax({
                async: false,
                type:"POST",
                dataType:"JSON",
                data:data,
                url:url,
                success:function (obj) {
                    form.val('myfrom',obj);
                    $("#prePic").prop("src",obj.userImg);
                    //角色复选框赋值
                    if(obj.roleIdAll.length>0){
                        for(var i=0;i<obj.roleIdAll.length;i++){
                            console.info(obj.roleIdAll[i])
                            $("input[name='role']").each(function(){
                                if($(this).val()==obj.roleIdAll[i]){
                                    $(this).prop('checked',true);
                                }
                            });
                            layui.form.render();
                        }
                    }
                    console.info(obj);
                },
                error:function () {

                }
            });
        }



        //表单取值
        layui.$('#LAY-component-form-getval').on('click', function(){
            var data = form.val('example');
            alert(JSON.stringify(data));
        });


        $(function () {
            //文件查看
            $('#imgFile').change(function () {
                //获取input file的files文件数组;
                //$('#usersImage')获取的是jQuery对象，.get(0)转为原生对象;
                //这边默认只能选一个，但是存放形式仍然是数组，所以取第一个元素使用[0];
                var file = $('#imgFile').get(0).files[0];
                //创建用来读取此文件的对象
                var reader = new FileReader();
                //使用该对象读取file文件
                reader.readAsDataURL(file);
                //读取文件成功后执行的方法函数
                reader.onload = function (e) {
                    //读取成功后返回的一个参数e，整个的一个进度事件
                    console.log(e);
                    //选择所要显示图片的img，要赋值给img的src就是e中target下result里面
                    //的base64编码格式的地址
                    $('#prePic').get(0).src = e.target.result;
                }
            });
        })

    });
    /**
     得到地址栏的参数
     */
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
</script>

</html>
